package com.yangfan.cloudalibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.yangfan.cloudalibaba.handler.BlockHandler;
import com.yangfan.cloudalibaba.service.SentinelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/provider")
@Slf4j
@RefreshScope //支持动态刷新
public class PaymentController {

    @Value("${server.port}")
    private String port;



    @GetMapping(value = "/nacos/{id}")
    public String getPayment(@PathVariable(value = "id") Long id) {
        return "nacos regisstry , serverPort: " + port;
    }



    @Value("${config.info}")
    private String info;


    // Nacos 自动配置 获取 动态配置 信息 案例

    /**
     * Nacos动态刷新 读取配置
     * @return
     */
    @GetMapping(value = "/nacos/getInfo")
    public String getInfo()
    {
        return "nacos regisstry , serverPort: " + port + "配置内容为："+info;
    }


    // Sentinel 案例


    @Autowired
    private SentinelService service;


    /**
     * 测试降级的方法
     * @param name
     * @return
     */
    @GetMapping(value = "/sentinel/hello/{name}")
    @SentinelResource(value = "sayHello",blockHandler = "sayHelloFallback",blockHandlerClass = BlockHandler.class)// 指定哪个类 下面的哪个降级方法处理 降级 这样能够 减少 代码的耦合度
    public String apiHello(@PathVariable String name) {
        return service.sayHello(name + "port : " + port);
    }




    /**
     * 原方法
     * 热点规则测试方法 如果满足热点规则则 会触发降级 熔断
     * @param p1
     * @param p2
     * @return
     */
    @GetMapping(value = "/sentinel/hotKey")
    @SentinelResource(value = "hotKey",blockHandler = "hotKeyHandler",fallback = "hotKeyFallback")
    public String testHotKey(
            @RequestParam(value = "p1",required = false) String p1 ,
            @RequestParam(value = "p2",required = false) String p2
    ){
        return "测试热点 key 正常返回" + "port : " + port;
    }

    /**
     * 限流触发
     * @param p1
     * @param p2
     * @param e
     * @return
     */
    public String hotKeyHandler(String p1,String p2,BlockException e){
        return "测试热点 key 降级的方法" + "port : " + port;
    }

    /**
     * 熔断触发
     * @param p1
     * @param p2
     * @param e
     * @return
     */
    public String hotKeyFallback(String p1,String p2,BlockException e){
        return "测试热点 key 报错的方法" + "port : " + port;
    }

}
